package com.zone.core.ext

import android.graphics.Rect
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible

/**
 * view被遮盖
 * @receiver View
 * @return Boolean
 */
fun View.isCovered(): Boolean {
    var currentView: View = this
    val currentViewRect = Rect()
    val partVisible: Boolean = currentView.getGlobalVisibleRect(currentViewRect)
    val totalHeightVisible: Boolean =
        currentViewRect.bottom - currentViewRect.top >= measuredHeight
    val totalWidthVisible: Boolean =
        currentViewRect.right - currentViewRect.left >= measuredWidth
    val totalViewVisible = partVisible && totalHeightVisible && totalWidthVisible
    if (!totalViewVisible) return true
    while (currentView.parent is ViewGroup) {
        val currentParent = currentView.parent as ViewGroup
        if (currentParent.visibility != View.VISIBLE) return true
        val start = currentView.indexOfInParent()
        for (i in start + 1 until currentParent.childCount) {
            val viewRect = Rect()
            getGlobalVisibleRect(viewRect)
            val otherView: View = currentParent.getChildAt(i)
            if(otherView.isVisible){
                val otherViewRect = Rect()
                otherView.getGlobalVisibleRect(otherViewRect)
                if (Rect.intersects(viewRect, otherViewRect)) return true
            }
        }
        currentView = currentParent
    }
    return false
}

fun View.indexOfInParent(): Int {
    var index = 0
    (parent as? ViewGroup)?.let {
        while (index < it.childCount) {
            if (it.getChildAt(index) === this) break
            index++
        }
    }
    return index
}